package backend;

import backend.inst.MipsComment;
import backend.inst.MipsEntry;
import backend.inst.MipsInst;

import java.io.PrintStream;
import java.util.ArrayList;
import java.util.List;

public class Target {


    private final List<Data> dataList = new ArrayList<>();
    private final List<MipsEntry> textList = new ArrayList<>();

    public void addData(Data data) {
        dataList.add(data);
    }

    public List<Data> getDataList() {
        return dataList;
    }

    public void deleteLastData() {
        dataList.remove(dataList.size() - 1);
    }

    public void addCode(MipsEntry entry) {
        textList.add(entry);
    }

    /**
     * 删除指定行数的asm代码
     *
     * @param num 删除的行数
     */
    public void deleteCode(int num) {
        textList.subList(textList.size() - num, textList.size()).clear();
    }

    public void dump(PrintStream out, boolean debugMode) {
        printDataSection(out);
        printTextSection(out, debugMode);
    }

    private void printDataSection(PrintStream out) {
        out.println(".data");
        dataList.forEach(out::println);
        out.println();
    }

    private void printTextSection(PrintStream out, boolean debugMode) {
        out.println(".text");
        out.println("\tla $ra end.end");
        out.println("\tj main");

        textList.stream()
                .filter(text -> !(text instanceof MipsComment && !debugMode))
                .forEach(text -> {
                    if (text instanceof MipsInst || text instanceof MipsComment) {
                        out.print("\t");
                    }
                    out.println(text);
                });

        out.println("end.end:");
    }
}
